from time import time
from traceback import format_exc
from urllib import unquote
from uuid import uuid4
from hashlib import sha1
import hmac,sys
import base64
import zmq
from eventlet import Timeout
from swift.common.swob import Response, Request
from swift.common.swob import HTTPBadRequest, HTTPForbidden, HTTPNotFound, \
    HTTPUnauthorized
import json,time
from swift.common.middleware.acl import clean_acl, parse_acl, referrer_allowed
from swift.common.utils import cache_from_env, get_logger, \
    split_path, config_true_value

context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("ipc://guard_app.ipc")
count_table={}

def current_time():
	return time.time()

def get_counter(poid):
	return count_table[poid]

fake_policy={}
fake_policy["id"]=1
fake_policy["subject"]="test"
fake_policy["object"]="test"
fake_policy["container"]="test"
fake_policy["method"]=["GET","PUT","POST","DELETE"]
fake_policy["decision"]="ALLOW"

policy_store={}
policy_store[1]=fake_policy
count_table[1]=0
def lookup(msg):
	subject=msg["account"]
	obj=msg["obj"]
	container=msg["container"]
	method=msg["method"]
	#print subject,obj,method
	for k  in policy_store:
		p=policy_store[k]
		if method=="HEAD":
			return "ALLOW",k
		if subject==p["subject"] and container==p["container"] and method in p["method"]:
			count_table[k]+=1
			return p["decision"],k
	return "ALLOW",None

def state_lookup(match_id):

	c=get_counter(match_id)
	#print count_table,c
	if c>=10:
		return "DENY"
	else:
		return "ALLOW"


auth={}
auth["admin:admin"]={"url":"$HOST/v1/AUTH_admin","key":"admin"}
auth["test:test1"]={"url":"$HOST/v1/AUTH_test","key":"test1"}
auth["test:test2"]={"url":"$HOST/v1/AUTH_test","key":"test2"}
auth["test2:tester"]={"url":"$HOST/v1/AUTH_test2","key":"tester"}
while True:
    #  Wait for next request from client
	message = socket.recv()
	if message.startswith("AUTH:"):
		tmp,account,user,key=message.split(":")
		uid=account+":"+user
		print message,uid
		if uid in auth:
			if auth[uid]["key"]==key:
				socket.send(auth[uid]["url"])
			else:
				socket.send("DENY")
		else:
			print "aaaaa"
			socket.send(str("DENY"))
	else:
		res=""
		
		#print "Received request: ", message,type(message)
		try:
			req=json.loads(message)
				#print type(req)
			#for k in req:
				#print k,req[k]
			print req
			res,match_id=lookup(req)
			if match_id:
				res_st=state_lookup(match_id)
				
				if res_st=="DENY":
					res=res_st
			#res="ALLOW"
			#print res

		except:
			e = sys.exc_info()[0]
			print "error",str(e)
			pass
		#res="ALLOW"
		print count_table
		socket.send("%s" % res)


